// pages/camera/camera.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    images: [],
    imgs: [],
    people: [
      {
        value: 0,
        name: '否',
      },
      {
        value: 1,
        name: '是',
      },
    ],
    name: [
      {
        value: 1,
        name: '是',
      },
    ],
    chooseLoaction: 0,
    location: '',
    current_x_coordinate: 123.287682,
    current_y_coordinate: 44.124004,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onReady: function (e) {
    this.mapCtx = wx.createMapContext('map')
  },
  mapclick: function () {
    var that = this;
    console.log("地图点击");
    that.ifLocation()
  },

  chooseLoaction() {
    let that = this
    wx.chooseLocation({
      success: function (res) {
        console.log("地图点击事件：" + JSON.stringify(res));
        var user_longitude = res.longitude;
        var user_lagitude = res.latitude;
        var user_address = res.address;
        var nowAddress = {};
        nowAddress["name"] = res.name;
        nowAddress["desc"] = res.address;
        that.setData({
          current_y_coordinate: user_lagitude,
          current_x_coordinate: user_longitude,
          addressName: user_address,
          textData: nowAddress,
        });
        //移动marker
        that.mapCtx.moveToLocation();
      },
      success: function (res) {        // complete
        console.log(res)
        that.setData({
          address: res.address,
          chooseLoaction: 1,
          current_x_coordinate: res.longitude,
          current_y_coordinate: res.latitude
        })
      },
    })
  },

  ifLocation() {
    let that = this
    wx.getSetting({
      success: (res) => {
        console.log(res)
        if (res.authSetting['scope.userLocation'] == true) {
          that.chooseLoaction()
        } else {
          wx.showModal({
            title: '授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    console.log('......')
                    if (res.authSetting["scope.userLocation"] === true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  },

  // mapclick(e){
  //   wx.getLocation({
  //     type: 'gcj02', //返回可以用于wx.openLocation的经纬度
  //     success (res) {
  //       console.log(res)
  //       // wx.openLocation({
  //       //   latitude:res.latitude,
  //       //   longitude:res.longitude,
  //       //   scale: 18,
  //       // })
  //     }
  //    })
  // },

  peopleChange(e) {
    let item1 = this.data.people
    for (let i = 0, len = item1.length; i < len; ++i) {
      item1[i].checked = item1[i].value === e.detail.value
    }
    this.setData({
      item1
    })
  },

  nameChange(e) {
    let item1 = this.data.people
    for (let i = 0, len = item1.length; i < len; ++i) {
      item1[i].checked = item1[i].value === e.detail.value
    }
    this.setData({
      item1
    })
  },

  // 图片操作的具体函数
  ImageOperator() {
    wx.chooseImage({
      count: 5,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 上传的图片数据
        let imgList = res.tempFilePaths;
        // 原始的图片数据
        let imageList = this.data.images;
        // 原来的图片数量
        let imageLength = imageList.length;
        // 当前的图片数量
        let nowLength = imgList.length;
        if (imageLength < 5) {
          let images = [];
          // 获取缺少的图片张数
          let residue = 5 - imageLength;
          // 如果缺少的张数大于当前的的张数  
          if (residue >= nowLength) {
            // 直接将两个数组合并为一个  
            images = imageList.concat(imgList);
          } else {
            // 否则截取当前的数组一部分  
            images = imageList.concat(imgList.slice(0, residue));
          }
          this.setData({
            images,
          })
        }
      }
    })
  },
  // 图片获取
  chooseImage() {
    this.ImageOperator()
  },
  // 删除图片
  deleteImage(event) {
    //获取数据绑定的data-id的数据
    const nowIndex = event.currentTarget.dataset.id;
    let images = this.data.images;
    images.splice(nowIndex, 1);
    this.setData({
      images
    })
  },
  // 预览图片
  previewIamge(event) {
    const nowIndex = event.currentTarget.dataset.id;
    const images = this.data.images;
    wx.previewImage({
      current: images[nowIndex],  //当前预览的图片
      urls: images,  //所有要预览的图片
    })
  },

  formSubmit(e) {
    let access_token = wx.getStorageSync('access_token')
    let { contact_tel, content, if_connected, realname, title } = e.detail.value
    let { current_x_coordinate, current_y_coordinate, address } = this.data
    if (title == '') {
      wx.showToast({
        title: '标题不能为空！',
        icon: 'none'
      })
      return false
    }
    if (content == '') {
      wx.showToast({
        title: '内容不能为空！',
        icon: 'none'
      })
      return false
    }
    if (realname == '') {
      wx.showToast({
        title: '姓名不能为空！',
        icon: 'none'
      })
      return false
    }
    if (contact_tel == '') {
      wx.showToast({
        title: '电话不能为空！',
        icon: 'none'
      })
      return false
    }
    if (this.data.images.length == 0) {
      wx.showToast({
        title: '请上传图片！',
        icon: 'none'
      })
      return false
    }
    wx.showLoading({
      title: '加载中...',
    })
    // promise上传表单
    let promiseArr = []
    let uploadArr = []
    for (var i = 0; i < this.data.images.length; i++) {
      let promise = new Promise((resolve, reject) => {
        wx.uploadFile({
          filePath: this.data.images[i],
          name: 'file',
          url: 'https://baokang.wshoto.com/wx/upload',
          complete: (res) => {
            console.log(res)
            let resArr = JSON.parse(res.data).url
            uploadArr.push(resArr)
            this.setData({
              imgs: uploadArr
            })
            resolve(res)
          }
        })
      })
      promiseArr.push(promise)
    }
    Promise.all(promiseArr).then(res => {
      let images = this.data.imgs.join(';')
      wx.request({
        url: 'https://baokang.wshoto.com/wx/randomup',
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          access_token: access_token,
          title: title,
          content: content,
          contact_tel: contact_tel,
          if_realname: 1,
          realname: realname,
          images: images,
          if_connected: if_connected,
          current_x_coordinate: current_x_coordinate,
          current_y_coordinate: current_y_coordinate,
          address: address
        },
        success: (res) => {
          console.log(res)
          wx.hideLoading()
          if (res.data.code == 1) {
            wx.showModal({
              title: '提示',
              content: '提交成功',
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  wx.navigateBack()
                }
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false,
            })
          }
        }
      })
    })
  }
})